<?php

$action = $_POST["action"];
if(!$action){
	displayStyle();
	?>	
	<script type="text/javascript" language="javascript" src="datepicker.js"></script>
	<link rel="stylesheet" type="text/css" href="datepicker.css" />
	<form method="post" action="index.php">
		<label for="preduzece">ID preduzeća:</label><input type="text" name="preduzece" id="preduzece" size="5" />
		<label>OD: </label>
		<input type="text" name="datum_start" id="datum_start" value="datum..." />
		<a id="datum_start_select" href="javascript:void(0)" onClick="displayDatePicker('datum_start',this)">&#9658;</a>
		<label>DO: </label>
		<input type="text" name="datum_end" id="datum_end" value="datum..." />
		<a id="datum_end_select" href="javascript:void(0)" onClick="displayDatePicker('datum_end',this)">&#9658;</a>
		<br clear="all" />
		<label>Max.</label><input name="max_items" id="max_items" type="text" maxlength="3" value="150" size="3" />
		<input type="submit" value="Kreiraj XML fajl..." />
		<input type="hidden" name="action" value="1" />
	</form>
	<?php
	die();
}

$preduzece_id	= $_POST["preduzece"];
$konto			= $_POST["konto"];

$datum_start	= $_POST["datum_start"];
$datum_end		= $_POST["datum_end"];
		$tmp = explode("/",$datum_start,3);
		$time_start = mktime(0,0,0,$tmp[1],$tmp[2],$tmp[0]);
		$tmp = explode("/",$datum_end,3);
		$time_end = mktime(0,0,0,$tmp[1],$tmp[2],$tmp[0]);

$max_items		= $_POST["max_items"];

/*require_once("adodb/adodb.inc.php");
$db = NewADOConnection('vfp');
$db->connect("foks", "", "");
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;*/

require_once("../classes/db_functions.php");
require_once("../classes/functions.php");
require_once("../classes/adrese.class.php");
$adr = new adrese();
$db = new db_functions();

$partner_ids = array();

$start = time();
$articles_there = array("VOJA");

//$q = "SELECT * FROM ugovor WHERE ugodat >= {^".$datum_start."} AND ugodat <= {^".$datum_end."} ORDER BY parid";
$q = "SELECT * FROM ugovori WHERE datum >= '".date("Y-m-d",$time_start)."' AND datum <= '".date("Y-m-d",$time_end)."' ORDER BY komitent";

$status = ($time_start < $time_end)?1:0;
if(!$preduzece_id){
	echo '<script>alert("Niste uneli ID preduzeca."); history.back();</script>';
	die();
}
if(!$status){
	echo '<script>alert("Prvi datum nije manji od drugog"); history.back();</script>';
	die();
}
$max_items = intval($max_items);
$maxnum = ($max_items>0)?$max_items:150;

$res = $db->select2($q); if($res===false){die("No results");}

$ukupno_ugovora = count($res);
if($ukupno_ugovora > $maxnum){
	echo '<script>alert("Za unete kriterijume ima '.$ukupno_ugovora.' ugovora!\nRedukujte kriterijume.\nMaksimalan broj ugovora po sesiji je '.$maxnum.'."); history.back();</script>';
	die();
}
$datum_exporta = date("Y-m-d",time());
$out_partneri = '<?xml version="1.0" standalone="yes"?>'."\r\n"
			   .'<PoslovniPartner xmlns="http://tempuri.org/PoslovniPartner.xsd">'."\r\n";
$out_ugovori = '<?xml version="1.0" encoding="utf-8"?>'."\r\n"
			   .'<IRExport xmlns="http://tempuri.org/IRExport.xsd">'."\r\n"
			   .'<fd_ir_export>'."\r\n"
			   .'<korisnik>Zute strane</korisnik>'."\r\n"
			   .'<adresa_korisnika />'."\r\n"
			   .'<mesto_korisnika>Beograd</mesto_korisnika>'."\r\n"
			   .'<preduzece>Zute strane</preduzece>'."\r\n"
			   .'<adresa_preduzeca></adresa_preduzeca>'."\r\n"
			   .'<mesto_preduzeca>Beograd</mesto_preduzeca>'."\r\n"
			   .'<pib_preduzeca>SR102036736</pib_preduzeca>'."\r\n"
			   .'<maticni_broj_preduzeca>17323776</maticni_broj_preduzeca>'."\r\n"
			   .'<sifra_preduzeca>'.$preduzece_id.'</sifra_preduzeca>'."\r\n"
			   .'<datum_eksporta>'.$datum_exporta.'</datum_eksporta>'."\r\n"
			   .'<knjiga_broj>1</knjiga_broj>'."\r\n"
			   .'<knjiga_naziv>1.Promet dobara i usluga u Republici</knjiga_naziv>'."\r\n"
			   .'<datum_od>'.date("Y-m-d",$time_start).'</datum_od>'."\r\n"
			   .'<datum_do>'.date("Y-m-d",$time_end).'</datum_do>'."\r\n"
			   .'<broj_dokumenata>'.$ukupno_ugovora.'</broj_dokumenata>'."\r\n"
			   .'<ima_broj_za_stampu>0</ima_broj_za_stampu>'."\r\n"
			   .'</fd_ir_export>'."\r\n";


$partneri_xml = getTemplate("partneri.xml");
$ugovori_xml = getTemplate("ugovori.xml");
$stavke_xml = getTemplate("stavka.xml");
$artikli_xml = getTemplate("artikl.xml");
$num=0;
foreach ($res as $row){
	$num++;
	$parid = trim($row["komitent"]);
	
	$ugo_id = trim($row["broj"]);
	$reg = '/\d{1,}/is';
	$ugo_id_noslash = $num;
	
	$ugo_br = trim($row["broj"]);
	if(!preg_match('/^\d{1,}$/',$ugo_br)){
		$tmp = preg_split('/(\d{1,})/',$ugo_br,-1,PREG_SPLIT_DELIM_CAPTURE);
		$new="";
		foreach($tmp as $v){
			if(preg_match('/^\d{1,}$/',$v)){
				$new .= $v;
			}else{
				switch(strtolower($v)){
					case 'p':
						$new .= 5;
						break;
					case 'grati':
					case 'g':
						$new .= 6;
						break;
				}
			}
		}
		$ugo_br = $new;
	}
	$broj_dokumenta = $ugo_br;
	
	$tmp = explode(" ",$row["datum"]);
	$ugo_datum = $tmp[0];
	$tmp = explode("-",$ugo_datum);
	$ugo_godina = $tmp[0];
	$ugo_mesec = $tmp[1];
	$ugo_dan = $tmp[2];

	$sql = "SELECT max(datum) as rok FROM ugovori_plan_otplate upo, ugovori_plan_rate upr "
		  ."WHERE upo.plan_id=upr.rata_plan "
		  ."AND upo.ugovor_id=".$row["id"];
	$ugo_rok = $db->getOne($sql);
	if(!$ugo_rok){
		$ugo_rok = $ugo_datum;
	}else{
		$ugo_rok = date("Y-m-d",$ugo_rok);
	}
			
	$ugo_cena_neto = trim($row["iznos_neto"]);
	$ugo_cena_korig = trim($row["iznos_popust"]);
	$ugo_porez = trim($row["iznos_porez"]);
	
	$upla_bez_por = $db->getOne("SELECT SUM(iznos_bp) FROm ugovori_otplate WHERE ugoid=".$row["id"]);
	$upla_por = $upla_bez_por*0.18;	
	
	$ugo_cena_neto = fixDelimiter($ugo_cena_neto);
	$ugo_cena_korig = fixDelimiter($ugo_cena_korig);
	$ugo_porez = fixDelimiter($ugo_porez);
	$upla_bez_por = fixDelimiter($upla_bez_por);
	$upla_por = fixDelimiter($upla_por);
	
	if(array_search($parid,$partner_ids) === false){
		array_push($partner_ids,$parid);
					
		$q = "SELECT * FROM komitenti WHERE komitent_id=$parid";
		$r_partner = $db->getRow($q,true);
		
		$par_naziv_short = trim($r_partner["komitent_name"]);
		$par_naziv_long = trim($r_partner["komitent_name1"]);
		
		$par_naziv_short = str_replace("&","&amp;",$par_naziv_short);
		$par_naziv_long = str_replace("&","&amp;",$par_naziv_long);
		
		$ADRESA_RES = $adr->getAll($r_partner["komitent_adresa"]);
		$par_adresa = $ADRESA_RES["ulica"]." ".$ADRESA_RES["broj"];
		$par_mesto_id = $ADRESA_RES["lokacija"]["mesto"]["id"];
		$par_tel = $db->getOne("SELECT telefon FROM komitenti_telefoni WHERE kom_id=$parid AND del_id=0 AND fax=0 ORDER BY `order` LIMIT 1");
		$par_fax = $db->getOne("SELECT telefon FROM komitenti_telefoni WHERE kom_id=$parid AND del_id=0 AND fax=1 ORDER BY `order` LIMIT 1");
		$par_email = $db->getOne("SELECT email FROM komitenti_emails WHERE kom_id=$parid AND del_id=0 LIMIT 1");
		$par_pib = $r_partner["komitent_pib"];
		
		$par_mesto = $ADRESA_RES["lokacija"]["mesto"]["name"];
		if($ADRESA_RES["lokacija"]["mesto"]["ptt"]){
			$par_mesto = $ADRESA_RES["lokacija"]["mesto"]["ptt"]." ".$par_mesto;
		}
		
		$arr = parseTemplate($partneri_xml);
		foreach($arr as $v){
			if(preg_match('/^</',$v)){
				$out_partneri .= $v;
			}else{
				$$v = trim($$v);
				if(!strlen($$v)){
					$out_partneri .= "0";
				}else{
					$out_partneri .= $$v;
				}
			}
		}
		$out_partneri .= "\n";
	}
	$ir_title = "$ugo_br - $par_naziv_short($parid)";
	$arr = parseTemplate($ugovori_xml);
	foreach($arr as $v){
		if(preg_match('/^</',$v)){
			$out_ugovori .= $v;
		}else{
			$$v = trim($$v);
			if(!strlen($$v)){
				$out_ugovori .= "0";
			}else{
				$out_ugovori .= $$v;
			}
		}
	}
	$out_ugovori .= "\r\n";
	
	// STAVKE
	$ret = getStavke($row["id"],$ugo_id_noslash,$articles_there);
	$items = $ret["items"];
	$articles = $ret["articles"];
	$articles_there = $ret["there"];
	
	$out_stavke = "";
	if(count($items)>0){
		foreach($items as $stavka){
			$stavka_id = $stavka->id;
			$stavka_rb = $stavka->rb;
			$stavka_base = $stavka->base;
			$stavka_tax = $stavka->tax;
			$stavka_t_rate = $stavka->t_rate;
			$stavka_price = $stavka->price;
			$stavka_p_one = $stavka->p_one;
			$stavka_art_id = $stavka->art_id;
			$stavka_art_name = $stavka->art_name;
			$stavka_rabat = $stavka->rabat;
			$stavka_kol = $stavka->kol;
			
			$stavke_tpl = parseTemplate($stavke_xml);
			$tmp = implode("",$stavke_tpl);
			$tmp = str_replace('$ugo_id_noslash',$ugo_id_noslash,$tmp);
			foreach($stavka as $k=>$v){
				$tmp = str_replace('$stavka_'.$k,$v,$tmp);
			}
			$out_stavke .= $tmp."\r\n";
		}
		$out_ugovori .= $out_stavke;
	}
	
	// ARTIKLI
	$out_artikli = "";
	if(count($articles) > 0){
		foreach ($articles as $artikl){
			$artikl_id = $artikl->artikl_id;
			$artikl_name = $artikl->artikl_name;
			$artikli_tpl = parseTemplate($artikli_xml);
			$tmp = implode("",$artikli_tpl);
			foreach ($artikl as $k=>$v){
				$tmp = str_replace('$'.$k,$v,$tmp);
			}
			$out_artikli .= $tmp."\r\n";
		}
		$out_ugovori .= $out_artikli;
	}
}
$out_partneri .= '</PoslovniPartner>';
	
// KRAJ CELOG DOKUMENTA
$out_ugovori .= '</IRExport>';

//$out_partneri = prepareForDisplay($out_partneri);
//$out_ugovori  = prepareForDisplay($out_ugovori);

switch($_GET['d']){
	case 'xml':
		displayXML($out_partneri);
		break;
	case 'html':
		displayHTML($out_partneri);
		echo "********************************************************************************";
		displayHTML($out_ugovori);
		break;
	default:
		writeFile("ugovori.xml",$out_ugovori);
		writeFile("partneri.xml",$out_partneri);
		displayStyle();
		?>
		<div style="float:left; background:#FFFF99; border:1px solid #000; margin:20px; padding:10px;">
			<p>Preduzeće: <?php echo $preduzece_id ?></p>
			<p><?php echo date("d.M.Y",$time_start) ?> - <?php echo date("d.M.Y",$time_end) ?></p>
			<p>Ukupno ugovora: <?php echo $ukupno_ugovora ?></p>
			
			<ol>
				<li><a href="ugovori.xml" title="Right click and &quot;Save Link As...&quot;">ugovori.xml</a></li>
				<li><a href="partneri.xml" title="Right click and &quot;Save Link As...&quot;">partneri.xml</a></li>
			</ol>
			<a href="javascript:history.back()">&nbsp;&nbsp; nazad</a>
		</div>
		<div id="uputstvo">
			<h2>Uputstvo za pripremu fajla za uvoz</h2>
			<ol>
				<li>Desni klik na fajl pa "Open With" pa odaberite Notepad</li>
				<li>Iz Notepad-a idite na "File/Save As..."</li>
				<li>U polju "Save as type" odaberite "All Files"</li>
				<li>U polju "Encoding" odaberite UTF-8</li>
				<li>Kliknite na Save</li>
			</ol>
		</div>
		<?php
		break;
}

function displayHTML($content){
	header("Content-Type: text/html charset=utf-8");
	echo $content;
}
function displayXML($content){
	header("Content-Type: text/xml charset=utf-8 \r\n");
	header("Content-Disposition: attachment \r\n");
	echo $content;
}
function writeFile($name,$content){
	$f = fopen($name,"w");if(!$f){die("Error opening file \"$name\".");}
	$written = fwrite($f,$content);
	if(!$written){die("Error writing to file \"$name\" following text:<br />$content.");}
}
function getTemplate($url){
	$f = file("templates/".$url);
	$f = implode("",$f);
	return $f;
}
function parseTemplate($file){
	$reg = '/{{(.*?)}}/';
	$ret = array();
	$ret = preg_split($reg,$file,-1,PREG_SPLIT_DELIM_CAPTURE);
	return $ret;
}
function prepareForDisplay($str){
	$str = str_replace(' ','?',$str);
	$str = str_replace(' ','?',$str);
	$str = str_replace(' ','?',$str);
	$str = str_replace(' ','?',$str);
	//$str = str_replace(' ',' ',$str);
	//$str = str_replace(' ',' ',$str);
	//$str = str_replace('?','?',$str);
	//$str = str_replace('?','?',$str);
	//$str = str_replace(' ',' ',$str);
	//$str = str_replace(' ',' ',$str);
	return $str;
}
function fixDelimiter($price){
	if(preg_match('/\./',$price) && strlen($price)){
		$tmp = explode(".",$price,2);
		if(strlen($tmp[1]) > 2){
			$tmp[1] = substr($tmp[1],0,2);
		}
		$price = implode($tmp,".");
	}
	return $price;
}
function getStavke($ugo_id,$ugo_id_noslash,$there){
	global $db;
	
	$sql = "SELECT * FROM ugovori_stavke WHERE ugovor_id=$ugo_id";
	/*$sql = "SELECT ugostv.ugskol, ugostv.ugscart, ugostv.ugscen, ugostv.ugspor, ugostv.ugspopust, ugostv.artid as artikl, art.artnaz "
		."FROM art,ugostv WHERE ugostv.artid=art.artid AND ugoid='".$ugo_br."'";*/
	$res = $db->select2($sql); if ($res === false) {return;}
	$i=0;
	foreach ($res as $row){
		$i++;
		if($row["iznos_neto"] && $row["iznos_bruto"]){
			$stavka = new stavka_ugostv();
			$stavka->id = $i;
			$stavka->ugovor_id = $ugo_id;
			$stavka->rb = $i;
			// kolicina
			$stavka->kol = $row["kolicina"];
			$stavka->kol = $stavka->kol>0 ? $stavka->kol : 0;
			// osnovica
			$stavka->base = bcdiv($row["iznos_bruto"],1.18,2);
			//$stavka->base = $stavka->base>0 ? ($stavka->base-$stavka->rabat) * $stavka->kol : 0;
			// rabat
			/*if($stavka->base){
				$stavka->rabat = ($stavka->base-(bcdiv($stavka->price,1.18,2)))*bcdiv(1,$stavka->base,2);
			}else{
				$stavka->rabat = 0;
			}*/
			//$stavka->rabat = bcdiv(trim($res->fields["ugspopust"]),trim($res->fields["ugscen"]),2);
			$nto = $row["iznos_neto"];
			$tmp = $nto - $stavka->base;
			if($nto)
				$stavka->rabat = bcdiv($tmp,$nto,2);
			else 
				$stavka->rabat = 0;
			// bruto
			$stavka->price = $row["iznos_bruto"];
			$stavka->price = $stavka->price>0 ? $stavka->price : 0;
			
			// iznos PDV
			$stavka->tax = ($stavka->price/1.18)*0.18;
			// artikl id
			$stavka->art_id = $row["artikl"];
			// artikl name
			if ($row["paket"]>0) {
				$stavka->art_name = $db->getOne("SELECT paketname FROM artikli_paketi WHERE paketid=".$row["artikl"]." LIMIT 1");
			}else{
				$cena = $db->getRow("SELECT * FROM cene WHERE cena_id=".$row["artikl"]." LIMIT 1",true);
				$artname = $db->getOne("SELECT art_name FROM artikli WHERE art_id=".$cena["cena_art_id"]." LIMIT 1");
				if ($cena["cena_art_tip"]>0) {
					$artname .= " - ".$db->getOne("SELECT arttip_name FROM artikli_tipovi WHERE arttip_id=".$cena["cena_art_tip"]." LIMIT 1");
				}
				if ($cena["cena_art_boja"]>0) {
					$artname .= " - ".$db->getOne("SELECT art_boja_code FROM artikli_boje WHERE art_boja_id=".$cena["cena_art_boja"]." LIMIT 1");
				}
				/*if ($cena["cena_art_jed_mere"]>0) {
					$artname .= " - ".$cena["cena_art_mera"]
							 ." ".$db->getOne("SELECT unit_svalue FROM jedinice_mere WHERE unit_id=".$cena["cena_art_jed_mere"]." LIMIT 1");
				}*/
				$stavka->art_name = $artname;
			}
			// prodajna jedinicna cena
			/*if($stavka->kol){
				$stavka->p_one = bcdiv($stavka->price,$stavka->kol,2);
			}else{
				$stavka->p_one = $stavka->price;
			}*/
			$stavka->p_one = $row["iznos_neto"];
			$stavke[] = $stavka;
			$search = array_search($stavka->art_id,$there);
			if(!$search){
				$artikl = new artikl_ugostv();
				$artikl->artikl_id = $stavka->art_id;
				$artikl->artikl_name = $stavka->art_name;
				$artikli[] = $artikl;
				$there[]=$stavka->art_id;
			}
		}
	}
	$ret["items"] = $stavke;
	$ret["articles"] = $artikli;
	$ret["there"] = $there;
	
	return $ret;
}
function displayStyle(){
?>
<style>
	h2{margin:0px; padding:5px; font-style:italic; font-size:15px;}
	p{margin:0px; padding:5px;}
	body{font-family:Arial, Helvetica, sans-serif; font-size:12px; background:#FFF000;}
	label{padding:7px 0px 0px 0px; margin:0px; display:block; float:left; clear:both}
	input{margin:5px; float:left; font-size:12px;}
	input[disabled]{background:none; border:none; color:#000; padding:3px 0px 0px 0px; width:70px; font-weight:bolder; text-align:center;}
	a, a:visited{color:Highlight; font-weight:bolder; text-decoration:none; padding:1px 2px; margin:0px;}
	a:hover, a:active{background:Highlight; color:HighlightText;}
	a#datum_start_select,a#datum_end_select{display:block; float:left; margin-top:6px;}
	ol{margin:5px; padding:0px 5px 0px 30px;}
	li{margin:0px; padding:2px 5px;}
	div#uputstvo{float:left; margin:20px 20px 20px 10px; border:1px solid #555; padding:10px; background:#FFFF99; color:#555;}
	</style>
<?php
}

class stavka_ugostv{
	public $id;
	public $ugovor_id;
	public $rb;
	public $kol;
	public $base;
	public $tax;
	public $price;
	public $p_one;
	public $art_id;
	public $art_name;
	public $rabat;
	function stavka_ugostv(){
	}
}
class artikl_ugostv{
	public $artikl_id;
	public $artikl_name;
	function artikl_ugostv(){
	}
}
?>